package br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;

import br.ufpe.cin.msc.jrsj2.recommender.persistence.dao.ClientDAO;
import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Client;

public class JPAClientDAO implements ClientDAO {

	private EntityManager emf;

	public JPAClientDAO(EntityManager emf) {
		this.emf = emf;
	}

	@Override
	public Client create(Client client) {
		try {
			emf.getTransaction().begin();
			emf.persist(client);
			emf.getTransaction().commit();
			return client;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	@Override
	public Client findByHash(String hash) {
		try {
			return (Client) emf
					.createQuery("SELECT c FROM Client c WHERE c.hash = :hash")
					.setParameter("hash", hash).getSingleResult();
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	public Client get(Object id) {
		try {
			return (Client) emf
					.createQuery("SELECT c FROM Client c WHERE c.id = :id")
					.setParameter("id", id).getSingleResult();
		} catch (Exception ex) {
			return null;
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Client> loadAll() {
		return emf.createQuery("SELECT c FROM Client c").getResultList();
	}

	@Override
	public void removeByHash(String hash) {
		if (hash == null)
			return;

		Client client = findByHash(hash);

		if (client == null)
			return;

		try {
			emf.getTransaction().begin();
			emf.remove(client);
			emf.getTransaction().commit();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
